using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace MonitorPlatform.Data.Context
{
    public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<MonitoringDbContext>
    {
        public MonitoringDbContext CreateDbContext(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false)
                .AddJsonFile("appsettings.Development.json", optional: true)
                .Build();

            var optionsBuilder = new DbContextOptionsBuilder<MonitoringDbContext>();
            var connectionString = configuration.GetConnectionString("DefaultConnection");
            
            // 如果配置文件中没有连接字符串，使用默认的本地SQL Server连接字符串
            if (string.IsNullOrEmpty(connectionString))
            {
                connectionString = "Server=(localdb)\\mssqllocaldb;Database=MonitorPlatform;Trusted_Connection=true;MultipleActiveResultSets=true";
            }

            optionsBuilder.UseSqlServer(connectionString, options =>
            {
                options.EnableRetryOnFailure(
                    maxRetryCount: 5,
                    maxRetryDelay: TimeSpan.FromSeconds(30),
                    errorNumbersToAdd: null);
                options.CommandTimeout(60);
                options.MigrationsAssembly("MonitorPlatform.Data");
            });

            // 添加敏感数据日志记录（仅限开发环境）
            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
            {
                optionsBuilder.EnableSensitiveDataLogging();
                optionsBuilder.EnableDetailedErrors();
            }

            return new MonitoringDbContext(optionsBuilder.Options);
        }
    }
} 